// iTod: iToDoList javascript core
// --------------------------------------------------------
// Version 1.0.20080612
// Code by iHao - www.ihao.net
// --------------------------------------------------------
// Description: just for fun

var iTod = {
	opts : {
		licls		:'div.PL div.b ul li.n',
		tglcls		:'h3.tgl',
		tnewcls		:'.Tnewt',
		tdonecls	:'.Tdonet',
		tudonecls	:'.Tudonet',
		tdelcls		:'.Tdelt',
		pnewcls		:'.Tnewp',
		pdelcls		:'.Tdelp'
	},
	init : function (options) {
	   iTod.opts = $.extend({}, iTod.opts, options);
	   iTod.ccli();
	   iTod.ccinput();
	   iTod.Lbtntgl();
	   iTod.Ltgl();
	   iDB.init();
	   //tod actions
	   iTod.Lnewt();
	   iTod.Ldonet();
	   iTod.Ludonet();
	   iTod.Ldelt();
	   iTod.Lnewp();
	   iTod.Ldelp();
	},
	ccli : function () {
		$.listen('mouseover',iTod.opts.tglcls,function(){
			$(this).removeClass('cdf').addClass('cd6');
		});
		$.listen('mouseout',iTod.opts.tglcls,function(){
			$(this).removeClass('cd6').addClass('cdf');
		});
	},
	ccinput : function () {
		$.listen('focus','input',function(){
			$(this).addClass('ifcs');
		});
		$.listen('blur','input',function(){
			$(this).removeClass('ifcs');
		});
		$.listen('mouseover','input',function(){
			$(this).addClass('ihvr');
		});
		$.listen('mouseout','input',function(){
			$(this).removeClass('ihvr');
		});
	},
	Lbtntgl : function () {
		$.listen('click','.showabout',function(){
			iDB.showtotalrow();
			//iDB.showtotalinfo();
		});
		/*
		$.listen('click','.showabout',function(){
			if ($(this).attr('rel') == 'show') {
				$(this).removeAttr('rel');
				$('.SMY').slideUp();
			} else {
				$(this).attr('rel','show');
				$('.SMY').slideDown();
			}
		});
		*/
	},
	Ltgl : function () {
		$.listen('click',iTod.opts.tglcls,function(){
			if ($(this).attr('rel') == 'show') {
				$(this).removeAttr('rel');
				$(this).next('ul').slideUp();
			} else {
				$(this).attr('rel','show');
				$(this).next('ul').slideDown();
			}
		});
	},
	Lnewt : function () {
		$.listen('click',iTod.opts.tnewcls,function(){
			this.blur();
			var Tname = $(this).prev('input').val();
			var fid = $(this).parents('div[rel]').attr('rel');
			iDB.insertnewtask(fid,Tname);
			Tname = null;
			fid = null;
			return false;
		});
	},
	Ldelt : function () {
		$.listen('click',iTod.opts.tdelcls,function(){
			this.blur();
			var Tid = $(this).parents('li').attr('rel');
			iDB.delTask(Tid);
			$(this).parents('li').remove();
			return false;
		});
	},
	Lnewp : function () {
		$.listen('click',iTod.opts.pnewcls,function(){
			this.blur();
			var Pname = $(this).prev('input').val();
			iDB.insertnewproject(Pname);
			return false;
		});
	},
	Ldelp : function () {
		$.listen('click',iTod.opts.pdelcls,function(){
			this.blur();
			var Pid =  $(this).parents('div[rel]').attr('rel');
			iDB.delProject(Pid);
			$(this).parents('div[rel]').remove();
			return false;
		});
	},
	Ldonet : function () {
		$.listen('click',iTod.opts.tdonecls,function(){
			this.blur();
			var T = $(UL).find('li[rel][class*=n]');
			var LI = $(this).parents('li[rel]');
			var UL = $(this).parents('ul');
			var Pid = $(this).parents('div[rel]').attr('rel');
			var Tid = $(this).parents('li[rel]').attr('rel');
			//alert(T.length);
			if (T.length > 1) { // just move this task to done block
				iDB.moveTaskToDone(Tid,Pid);
				$(LI).remove();
			} else { // all task done, move this project to done block
				//iDB.moveProjectToDone(id,fid);
				alert(T.length + ' : move project');
			}
			LI = null; UL = null; T = null; Pid = null; Tid = null;
			return false;
		});
	},
	Ludonet : function () {
		$.listen('click',iTod.opts.tudonecls,function(){
			this.blur();
			var T = $(this).parents('ul').find('li[rel][class*=n]');
			var LI = $(this).parents('li[rel]');
			var UL = $(this).parents('ul');
			var Pid = $(this).parents('div[rel]').attr('rel');
			var Tid = $(this).parents('li[rel]').attr('rel');
			//alert(T.length);
			if (T.length > 0) { // just move this task to undone block
				iDB.moveTaskToUndone(Tid,Pid);
				$(LI).remove();
			} else { // this project has undone, move this project to undone block
				alert(T.length + ' : move project');
			}
			LI = null; UL = null; T = null; Pid = null; Tid = null;
			return false;
		});
	}
}




/************************
 *
 * Google Gears Db Core
 *
*************************/
var iDB = {
	db	:null,
	O	:[],
	opts : {
		dbname		:'itod'
	},
	init : function (options) {
		iDB.opts = $.extend({}, iDB.opts, options);
		try {
			iDB.db = google.gears.factory.create('beta.database');
		} catch (ex) {
			// Gears not installed
			alert('Could not create database:\n\n' + ex.message);
			return;
		}

		iDB.db.open(iDB.opts.dbname);

		if (!(iDB.tools.getQueryInfo() || iDB.tools.getCookieInfo())) {
			iDB.buildNew();
		} else {
			iDB.listAll();
		}
	},
	buildNew : function () {
		//alert('new');
		iDB.tools.setCookieInfo(iDB.opts.dbname);
		iDB.db.execute('CREATE table if not exists tod (id int, fid int, stat int, content text, itime int)');
		iDB.db.execute('INSERT INTO tod VALUES (?, ?, ?, ?, ?)', [1, 0, 2, 'iToDoList', new Date().getTime()]);
		iDB.listAll();
	},
	listAll : function () {

		//iDB.db.execute('drop table tod');
		
		//iDB.db.execute('DELETE FROM tod WHERE id = (?)',[10]);

		//iDB.db.execute('UPDATE tod SET stat = 0, itime = ' + new Date().getTime() + ' WHERE id = 4');
		
		//iDB.showtotalinfo();
		//iDB.showtotalrow();
		
		iDB.listUndoneProject();
		iDB.listDoneProject();
	},
	listUndoneProject : function () {
		//select undone projects's id
		var prs = iDB.db.execute('SELECT * FROM tod WHERE fid = 1 and stat = 0 ORDER BY itime ASC');

		while (prs.isValidRow()) {
			iDB.buildNewUndoneProject(prs);
			iDB.listUndoneTask(prs.field(0));
			iDB.listDoneTask(prs.field(0));
			prs.next();
		}
		prs.close();
	},
	listDoneProject : function () {
		//select Done projects's id
		var prs = iDB.db.execute('SELECT * FROM tod WHERE fid = 1 and stat = 1 ORDER BY itime ASC');

		while (prs.isValidRow()) {
			iDB.buildNewDoneProject(prs);
			iDB.listDoneTask(prs.field(0));
			prs.next();
		}
		prs.close();
	},
	buildNewUndoneProject : function (rs) {
		var O = [];
		O.push('<div class="b cdd" rel="'+rs.fieldByName("id")+'">');
		O.push('<h3>'+rs.fieldByName("content")+' <a href="#" class="cred normal Tdelp">Del</a></h3><ul>');
		O.push('<li class="i"><input type="text" class="ce8" /><a href="#" class="cgreen Tnewt">New Task</a></li>');
		O.push('</ul></div>');
		$(O.join('')).appendTo('div.PL');
		var O = null;
	},
	buildNewDoneProject : function (rs) {
		var O = [];
		O.push('<div class="b cdd" rel="'+rs.fieldByName("id")+'">');
		O.push('<h3 class="tgl">'+rs.fieldByName("content")+' <a href="#" class="cred normal Tdelp">Del</a></h3><ul></ul></div>');
		$(O.join('')).appendTo('div.PD');
		var O = null;
	},
	listUndoneTask : function (fid) {
		var trsud = iDB.db.execute('SELECT * FROM tod where fid = ' + fid + ' AND stat = 0 ORDER BY itime ASC');
		while (trsud.isValidRow()) {
			iDB.buildNewUndoneTask(trsud,fid);
			trsud.next();
		}
		trsud.close();
	},
	listDoneTask : function (fid) {
		var trsd = iDB.db.execute('SELECT * FROM tod where fid = ' + fid + ' AND stat = 1 ORDER BY itime ASC');
		while (trsd.isValidRow()) {
			iDB.buildNewDoneTask(trsd,fid);
			trsd.next();
		}
		trsd.close();
	},
	buildNewUndoneTask : function (rs, fid) {
		var O = [];
		O.push('<li class="n cdf" rel="'+rs.fieldByName("id")+'">');
		O.push('<span class="l">'+rs.fieldByName("content")+'</span>');
		O.push('<span class="r"><a href="#" class="cgreen Tdonet">Done</a> | <a href="#" class="cred Tdelt">Del</a></span>');
		O.push('<div class="clear"></div></li>');
		$(O.join('')).prependTo('div[rel='+fid+'] ul');
		var O = null;
	},
	buildNewDoneTask : function (rs, fid) {
		var O = [];
		O.push('<li class="d cdf" rel="'+rs.fieldByName("id")+'">');
		O.push('<span class="l">'+rs.fieldByName("content")+'</span>');
		O.push('<span class="r"><a href="#" class="cred Tudonet">Undone</a> | <a href="#" class="cred Tdelt">Del</a></span>');
		O.push('<div class="clear"></div></li>');
		$(O.join('')).appendTo('div[rel='+fid+'] ul');
		var O = null;
	},
	moveTaskToDone : function (Tid,Pid) {
		//alert('begain update database');
		iDB.db.execute('UPDATE tod SET stat = 1, itime = ' + new Date().getTime() + ' WHERE id = ' + Tid);
		var rs = iDB.db.execute('SELECT * FROM tod WHERE id = ' + Tid);
		while (rs.isValidRow()) {
			iDB.buildNewDoneTask(rs,Pid);
			rs.next();
		}
		rs.close();
	},
	moveTaskToUndone : function (Tid,Pid) {
		//alert('begain update database');
		iDB.db.execute('UPDATE tod SET stat = 0, itime = ' + new Date().getTime() + ' WHERE id = ' + Tid);
		var rs = iDB.db.execute('SELECT * FROM tod WHERE id = ' + Tid);
		while (rs.isValidRow()) {
			iDB.buildNewUndoneTask(rs,Pid);
			rs.next();
		}
		rs.close();
	},
	delTask : function (id) {
		iDB.db.execute('DELETE FROM tod WHERE id = ' + id);
	},
	delProject : function (id) {
		iDB.db.execute('DELETE FROM tod WHERE id = ' + id + ' OR fid = ' + id);
	},
	insertnewproject : function (p) {
		var num = iDB.getmaxnum() - ( -1 ); // for new row id : (maxRowNum + 1)
		//alert(num);
		iDB.db.execute('INSERT INTO tod VALUES (?, ?, ?, ?, ?)', [num, 1, 0, p, new Date().getTime()]);
		var rs = iDB.db.execute('SELECT * FROM tod WHERE id = ' + num);
		while (rs.isValidRow()) {
			iDB.buildNewUndoneProject(rs);
			rs.next();
		}
		rs.close();
	},
	insertnewtask : function (fid,p) {
		var num = iDB.getmaxnum() - ( -1 ); // for new row id : (maxRowNum + 1)
		//alert(num);
		iDB.db.execute('INSERT INTO tod VALUES (?, ?, ?, ?, ?)', [num, fid, 0, p, new Date().getTime()]);
		var rs = iDB.db.execute('SELECT * FROM tod WHERE id = ' + num);
		while (rs.isValidRow()) {
			iDB.buildNewUndoneTask(rs,fid);
			rs.next();
		}
		rs.close();
	},
	getmaxnum : function () {
		var rs = iDB.db.execute('SELECT MAX(id) FROM tod');
		while (rs.isValidRow()) {
			return rs.field(0);
			rs.next();
		}
		rs.close();
	},
	showtotalrow : function () {
		var O = [];
		var rs = iDB.db.execute('SELECT * FROM tod');
		while (rs.isValidRow()) {
			O.push(rs.fieldName(0) + ' : ' + rs.field(0) + ' | ');
			O.push(rs.fieldName(1) + ' : ' + rs.field(1) + ' | ');
			O.push(rs.fieldName(2) + ' : ' + rs.field(2) + ' | ');
			O.push(rs.fieldName(3) + ' : ' + rs.field(3) + ' | ');
			O.push(rs.fieldName(4) + ' : ' + rs.field(4) + '\n\r');
			rs.next();
		}
		rs.close();
		alert(O.join(''));
	},
	showtotalinfo : function () {
		var O = [];
		O.push('Total information of this database : \n\r\n\r');
		var rs = iDB.db.execute('SELECT COUNT(*) FROM tod WHERE fid = 1 AND stat = 0');
		while (rs.isValidRow()) {
			O.push('Undone Project num : ' + rs.field(0) + '\n\r');
			rs.next();
		}
		rs.close();
		var rs = iDB.db.execute('SELECT COUNT(*) FROM tod WHERE fid = 1 AND stat = 1');
		while (rs.isValidRow()) {
			O.push('Done Project num : ' + rs.field(0) + '\n\r');
			rs.next();
		}
		rs.close();
		var rs = iDB.db.execute('SELECT COUNT(*) FROM tod WHERE fid > 1 AND stat = 0');
		while (rs.isValidRow()) {
			O.push('Undone Task num : ' + rs.field(0) + '\n\r');
			rs.next();
		}
		rs.close();
		var rs = iDB.db.execute('SELECT COUNT(*) FROM tod WHERE fid > 1 AND stat = 1');
		while (rs.isValidRow()) {
			O.push('Done Task num : ' + rs.field(0) + '\n\r');
			rs.next();
		}
		rs.close();
		alert(O.join(''));
	},
	tools : {
		getQueryInfo : function () {
			var res = /[?&]dbinfo\=([^&#]*)/.exec(window.location.href);
			return res && res[1];
		},
		getCookieInfo : function () {
			var res = /dbinfo\=([^\;\= ]+)/.exec(document.cookie);
			return res && res[1];
		},
		setCookieInfo : function (dbName) {
			var d = new Date();
			d.setMonth(d.getMonth() + 1);
			document.cookie = 'dbinfo=' + dbName + ';expires=' + d.toUTCString();
		},
		escapeHtml : function (s) {
			return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;');
		},
	}
}
